//
//  JDPlayVideoOrPictureView.swift
//  DragonWallet
//
//  Created by volantPig on 2024/7/25.
//

import UIKit

class JDPlayVideoOrPictureView: UIView {

    var lastImageV: UIImageView?
    var originalFrame: CGRect?
    var scrollView: UIScrollView?
    
    init(frame: CGRect, gesture: UITapGestureRecognizer, superView: UIView) {
        super.init(frame: frame)
        
        self.scrollView = UIScrollView(frame: UIScreen.main.bounds)
        self.scrollView?.backgroundColor = .orange
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapBgView(_:)))
        self.scrollView?.addGestureRecognizer(tap)
     
        let imgV = gesture.view as? UIImageView
        
        self.lastImageV = UIImageView()
        self.lastImageV?.image = imgV?.image
        self.lastImageV?.frame = self.scrollView?.convert(imgV?.frame ?? .zero, from: self) ?? .zero
        self.scrollView?.addSubview(self.lastImageV!)
        self.addSubview(self.scrollView!)
        
        self.originalFrame = self.lastImageV?.frame
        
        self.scrollView?.maximumZoomScale = 5
        self.scrollView?.delegate = self
        
        UIView.animate(withDuration: 0.5) {
            var subFrame = self.lastImageV?.frame
            subFrame?.size.width = self.scrollView?.frame.size.width ?? 0
            let subHeight = (self.scrollView?.frame.size.width ?? 0) * ((self.lastImageV?.image?.size.height ?? 1) / (self.lastImageV?.image?.size.width ?? 1))
            subFrame?.size.height = subHeight
            subFrame?.origin.x = 0
            subFrame?.origin.y = ((self.scrollView?.frame.size.height ?? 0) - subHeight) * 0.5
            self.lastImageV?.frame = subFrame ?? .zero
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tapBgView(_ tap: UITapGestureRecognizer) {
        self.scrollView?.contentOffset = .zero
        UIView.animate(withDuration: 0.5) {
            self.lastImageV?.frame = self.originalFrame ?? .zero
//            tap.view?.backgroundColor = .blue
        } completion: { finished in
            tap.view?.removeFromSuperview()
            self.removeFromSuperview()
            self.scrollView = nil
            self.lastImageV = nil
        }
    }
    
}

extension JDPlayVideoOrPictureView: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.lastImageV
    }
}
